import { Component, OnInit, Inject } from '@angular/core';
import * as moment from 'moment';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { AjaxResponse } from 'app/model/rest-model';
import { SignInInfo, WeekSignIn, SignIn } from 'app/model/signin-module';
import { ITokenService, DA_SERVICE_TOKEN } from '@delon/auth';

@Component({
  selector: 'app-signin',
  templateUrl: './signin.component.html',
  styles: []
})
export class SigninComponent implements OnInit {

  data: any[] = [];
  
  signInState = "未签到";
  curDay = moment(new Date()).format('YYYY-MM-DD'); // 当前日期
  week = ""; // 周几
  userSignInCount = 0; // 用户签到次数
  todaySignInCount = 0; // 今天签到统计
  weekSignIns: WeekSignIn[] = []; // 一周签到统计
  showBar = false; // 用于渲染图表

  userSignIn: SignIn = null;

  constructor(
    private http: HttpClient,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
  ) { }

  ngOnInit() {
    this.http.get("/signIn").subscribe(
      (val: AjaxResponse<SignInInfo>) => {
        if (val.responseCode.code == 200) {
          let data = val.data;
          if(data.haveSignInToday) this.signInState = "已签到";
          this.curDay = data.curDay;
          this.week = data.week;
          this.userSignInCount = data.userSignInCount;
          this.todaySignInCount = data.weekSignTotal[data.weekSignTotal.length-1].count;
          this.weekSignIns = data.weekSignTotal;
          this.showBar = true;
          // 一周签到统计
          const beginDay = new Date().getTime();
          for(let i = 0; i < this.weekSignIns.length; i += 1) {
            this.data.push({
              x: moment(new Date(this.weekSignIns[i].signDate)).format('YYYY-MM-DD') + "&nbsp;签到",
              y: this.weekSignIns[i].count,
            });
          }
        }
      }
    );
  }

  doSignIn(){
    if(this.signInState != "已签到") {
      this.http.get("/doSignIn").subscribe(
        (val: AjaxResponse<SignIn>) => {
          if (val.responseCode.code == 200) {
            this.userSignIn = val.data;
            this.signInState = "已签到"; 
            this.todaySignInCount++;
            this.userSignInCount++;
          }
        }
      );
    }
  }
}
